// @author: caoshi
// @date: 2021-06-17 21:19
package initialize

import (
	"academic/config"
	"academic/global"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 获取gorm 的数据库连接对象
func Gorm() *gorm.DB {
	return GormMysql()
}

func GormMysql() *gorm.DB {
	m := global.GvaConfig.Mysql // 数据库连接信息, 在yaml中配置的
	if m.Dbname == "" {
		return nil
	}
	dsn := config.Dsn(&m)
	mysqlConfig := mysql.Config{
		DSN:                       dsn,
		DefaultStringSize:         191,
		DisableDatetimePrecision:  true,
		DontSupportRenameIndex:    true,
		DontSupportRenameColumn:   true,
		SkipInitializeWithVersion: false,
	}
	if db, err := gorm.Open(mysql.New(mysqlConfig)); err != nil {
		return nil
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(m.MaxIdleConns)
		sqlDB.SetMaxOpenConns(m.MaxOpenConns)
		return db
	}

}
